package org.elip.stewiemaze.server.services;

import java.util.logging.Logger;

import org.elip.stewiemaze.client.FacebookService;
import org.elip.stewiemaze.server.DatastoreHelper;
import org.elip.stewiemaze.server.FacebookHelper;
import org.elip.stewiemaze.shared.entities.Player;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.restfb.exception.FacebookOAuthException;
import com.restfb.types.User;

public class FacebookServiceImpl extends RemoteServiceServlet implements FacebookService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public String getUsername(String accessToken) {
		Logger logger = Logger.getLogger(FacebookServiceImpl.class.getName());
		logger.fine("Retrieving username for facebook acces token : " + accessToken);
		String username;
		try {
			username = FacebookHelper.getUsername(accessToken);
		}
		catch (FacebookOAuthException e) {
			// accesToken is no longer valid, user removed this app from his preferences
			return null;
		}
		
		Player player = DatastoreHelper.getPlayer(username);
		if (player == null) {
			User user = FacebookHelper.getUser(accessToken);
			Player newFacebookPlayer = PlayerService.createFacebookPlayer(username, user.getId(), user.getEmail(), new Long(0));
			RegisterPlayerService.registerPlayer(newFacebookPlayer);
			DatastoreHelper.updateAccessToken(username, accessToken);
			FacebookHelper.postMessageToWall(username, "just registered to stewiemaze");
		}
		return username;
	}

}
